package cn.jit.ssm.service.impl;

import cn.jit.ssm.beans.entity.JitAccount;
import cn.jit.ssm.beans.entity.JitAccountExample;
import cn.jit.ssm.constant.SessionKey;
import cn.jit.ssm.mapper.JitAccountMapper;
import cn.jit.ssm.service.AccountService;
import cn.jit.ssm.support.JSONReturn;
import cn.jit.ssm.utils.CompareUtil;
import cn.jit.ssm.utils.EncryptUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author: Cecurio
 * @create: 2017-12-06 16:16
 **/
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private JitAccountMapper jitAccountMapper;

    /**
     * @param name
     * @param pass
     * @param request
     * @return
     */
    @Override
    public JSONReturn login(String name, String pass, HttpServletRequest request) {

        if (CompareUtil.isEmpty(name)) {
            return JSONReturn.buildFailure("登录失败, 用户名必填!");
        }

        if (CompareUtil.isEmpty(pass)) {
            return JSONReturn.buildFailure("登录失败, 密码必填!");
        }

        JitAccountExample query = new JitAccountExample();
        query.or().andAcctNameEqualTo(name);

        List<JitAccount> jitAccountList = jitAccountMapper.selectByExample(query);

        if (CompareUtil.isEmpty(jitAccountList)) {
            return JSONReturn.buildFailure("登录失败, 用户不存在!");
        }

        if (jitAccountList.size() != 1) {
            return JSONReturn.buildFailure("登录失败!");
        }

        JitAccount account = jitAccountList.get(0);
        if (CompareUtil.isEmpty(account) || account.getAcctDeleteState()) {
            return JSONReturn.buildFailure("登录失败, 用户不存在!");
        }

        if (!EncryptUtil.encodeMD5String(pass).equals(account.getAcctPassword())) {
            return JSONReturn.buildFailure("登录失败, 用户名或密码错误!");
        }

        request.getSession().setAttribute(SessionKey.MODULE_ACCTNAME, account.getAcctName());
        return JSONReturn.buildSuccess("登录成功!");
    }

    @Override
    public JSONReturn findAccountInfo(String acctName) {
        JitAccount jitAccount = jitAccountMapper.selectByPrimaryKey(1L);
        return JSONReturn.buildSuccess(jitAccount);
    }

    @Override
    public JitAccount findAccountByName(String userName) {
        if (StringUtils.isEmpty(userName)) {
            return null;
        }

        JitAccountExample query = new JitAccountExample();
        query.or().andAcctNameEqualTo(userName);

        List<JitAccount> jitAccountList = jitAccountMapper.selectByExample(query);

        if (CompareUtil.isEmpty(jitAccountList)) {
            return null;
        }

        if (jitAccountList.size() != 1) {
            return null;
        }

        JitAccount account = jitAccountList.get(0);

        return account;
    }
}
